package cn.qianxun.meta.word.util;

import com.aspose.pdf.DocSaveOptions;
import com.aspose.pdf.Document;
import com.aspose.pdf.FontSubsetStrategy;

import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * @Author fuzhilin
 * @Date 2022/11/24 22:19
 * @Description
 */
public class PdfToWord {


    /**
     * pdf 转word
     *
     * @param pdfInputStream pdf文件流
     * @param wordPath       word路径
     */
    public static void pdf2doc(InputStream pdfInputStream, String wordPath) {
        System.out.println("pdf转word开始...");
        long old = System.currentTimeMillis();
        try {
            //新建一个word文档
            String[] strArray = wordPath.split("\\.");
            if (strArray.length != 2) {
                throw new RuntimeException("文件名称格式不正确");
            }
            if (!"docx".equals(strArray[1])) {
                throw new RuntimeException("文件格式不正确");
            }
            FileOutputStream os = new FileOutputStream(wordPath);
            //doc是将要被转化的word文档
            Document doc = new Document(pdfInputStream);
            //获取所有用户的字体
            /*String userfontsfoloder;
            if (true) {
                userfontsfoloder = "C:\\Users\\Administrator\\AppData\\Local" + "\\Microsoft\\Windows\\Fonts\\";
            } else {
                userfontsfoloder = "/usr/share/fonts/Fonts";
            }
            List<String> localFontPaths = FontRepository.getLocalFontPaths();
            localFontPaths.add(userfontsfoloder);
            FontRepository.setLocalFontPaths(localFontPaths);
            FontRepository.loadFonts();*/
            doc.getFontUtilities().subsetFonts(FontSubsetStrategy.SubsetAllFonts);

            // 字体子集将嵌入完全嵌入的字体，但是未嵌入文档中的字体将不受影响。
           // doc.getFontUtilities().subsetFonts(allFontsNew);
            // Save resultant DOCX file
            DocSaveOptions saveOptions = new DocSaveOptions();

            // Set output format
            saveOptions.setFormat(DocSaveOptions.DocFormat.DocX);
            saveOptions.setAddReturnToLineEnd(true);

            // Set the recognition mode as Flow
            saveOptions.setMode(DocSaveOptions.RecognitionMode.Flow);

            // Set the horizontal proximity as 2.5
            saveOptions.setRelativeHorizontalProximity(2.5f);

            // Enable bullets recognition during conversion process
            saveOptions.setRecognizeBullets(true);
            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            doc.save(os, saveOptions);
            os.close();
            //转化用时
            long now = System.currentTimeMillis();
            System.out.println("Pdf 转 Word 共耗时：" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            System.out.println("Pdf 转 Word 失败...");
            e.printStackTrace();
        }
    }

}
